package com.lizi.core.util;


import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;

import org.apache.commons.beanutils.ContextClassLoaderLocal;



public class BeanUtilsExecute {


    // ------------------------------------------------------ Private Class Variables

    /** 
     * Contains <code>BeanUtilsBean</code> instances indexed by context classloader.
     */
    private static final ContextClassLoaderLocal 
            BEANS_BY_CLASSLOADER = new ContextClassLoaderLocal() {
                        // Creates the default instance used when the context classloader is unavailable
                        protected Object initialValue() {
                            return new BeanUtilsExecute();
                        }
                    };
    
    public static BeanUtilsExecute getInstance() {
        return (BeanUtilsExecute) BEANS_BY_CLASSLOADER.get();
    }


    public static void setInstance(BeanUtilsExecute newInstance) {
        BEANS_BY_CLASSLOADER.set(newInstance);
    }
  
    public BeanUtilsExecute() {
      
    }
    


    /**
     * <p>Populate the JavaBeans properties of the specified bean, based on
     * the specified name/value pairs.  This method uses Java reflection APIs
     * to identify corresponding "property setter" method names, and deals
     * with setter arguments of type <code>String</code>, <code>boolean</code>,
     * <code>int</code>, <code>long</code>, <code>float</code>, and
     * <code>double</code>.  In addition, array setters for these types (or the
     * corresponding primitive types) can also be identified.</p>
     * 
     *
     */
    public void populate(Object bean, Map<String,Object> properties) 
    		throws IllegalArgumentException, IllegalAccessException{

        // Do nothing unless both arguments have been specified
        if ((bean == null) || (properties == null)) {
            return;
        }
  	  
        Field[] fields = bean.getClass().getDeclaredFields();   
        Object val = null;
        for (Field field : fields) {    
            int mod = field.getModifiers();    
            if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){    
                continue;    
            }    
            val = properties.get(field.getName());
            if(val != null){
            	field.setAccessible(true);    
	            field.set(bean, properties.get(field.getName()));   
            } 
        }   
        
    }
 
   

}
